<template>
  <!-- 播放列表 -->
  <div class="list">
    <!-- 表头 -->
    <div class="listhd">
      <div class="listhdc">
        <h4 class="f-fl">播放列表({{ songList.length }})</h4>
        <a href="javascript:void(0);" class="likeall f-fl" @click.stop="operationClick"
          ><i class="u-icon-playlist"></i>收藏全部</a
        >
        <span class="line f-fl"></span>
        <a
          href="javascript:void(0);"
          class="clear f-fl"
          @click="$store.commit('Music/clearSongList')"
          ><i class="u-icon-playlist"></i>清除</a
        >
        <p class="f-fl">
          {{ currentSong.name ? currentSong.name : '' }}
        </p>
        <span
          class="close u-icon-playlist"
          @click="$store.commit('Music/setListDisplay', false)"
        ></span>
      </div>
    </div>
    <!-- 歌曲列表 -->
    <div class="listbd" ref="listbdRef">
      <img
        :src="'https://music.163.com/api/img/blur/' + currentSong.al.pic_str"
        alt=""
        v-if="currentSong.id"
      />
      <div class="msk"></div>
      <div class="listbdc" @mousewheel.prevent="listbdcWheel($event, 'ulRef', 'scrollRef')">
        <!-- 列表为空 -->
        <div class="nocnt" v-if="songList.length === 0">
          <i class="u-icon-playlist"></i> 你还没有添加任何歌曲<br />去首页
          <router-link to="/discover/">发现音乐</router-link>，或在
          <router-link to="/my/">我的音乐</router-link>收听自己收藏的歌单。
        </div>
        <!-- 列表 -->
        <ul v-if="songList.length !== 0" ref="ulRef">
          <li
            v-for="(item, index) in songList"
            :key="item.id + item.name"
            :class="index == playerSetting.index ? 'z-sel' : ''"
            @click="songListClickHandle(index)"
          >
            <div class="col col-1">
              <i class="u-icon-playlist playicn"></i>
            </div>
            <div class="col col-2">{{ item.name }}</div>
            <div class="col col-3">
              <div class="icns">
                <i class="u-icon-playlist del" @click.stop="delSong(item.id)"></i>
                <i class="u-icon-playlist dl" @click.stop="operationClick"></i>
                <i class="u-icon-playlist share" @click.stop="operationClick"></i>
                <i class="u-icon-playlist like" @click.stop="operationClick"></i>
              </div>
            </div>
            <div class="col col-4 f-thide">
              <span>
                <router-link
                  to=""
                  v-for="(ar, i) in item.ar"
                  :key="ar.id + ar.name"
                  :title="item.ar | arName"
                  >{{ i + 1 === item.ar.length ? ar.name : ar.name + '/' }}</router-link
                >
              </span>
            </div>
            <div class="col col-5">{{ item.dt | dtFormate2 }}</div>
            <div class="col col-6">
              <router-link to="" class="u-icon-playlist link">&nbsp;&nbsp;&nbsp;&nbsp;</router-link>
            </div>
          </li>
        </ul>
      </div>
      <!-- 滚动条 -->
      <div class="bline">
        <span
          class="scroll"
          :style="{ height: 260 * (10 / songList.length) + 'px' }"
          @mousedown="scrollHandle($event, 0)"
          ref="scrollRef"
        ></span>
      </div>
      <!-- 报错 -->
      <div class="ask">
        <a
          href="javascript:void(0);"
          class="u-icon-playlist"
          @click="uploadDisplay = !uploadDisplay"
        ></a>
      </div>
      <!-- 报错 -->
      <div class="upload" v-show="uploadDisplay" v-if="songList.length !== 0">
        <a
          :href="'https://music.163.com/lyric/report?id=' + currentSong.id"
          class="colse"
          @click="uploadDisplay = false"
          >报错</a
        >
      </div>
      <div class="msk2"></div>
      <!-- 歌词 -->
      <div class="listlyric" ref="listlyricRef">
        <div
          v-if="lyric.length && currentSong.id"
          class="lyc"
          ref="lycRef"
          @mousewheel.prevent="listbdcWheel($event, 'lycRef', 'scrollRef1')"
        >
          <p
            v-for="(item, i) in lyric"
            :key="currentSong.name + item.time + i"
            :data-time="item.time"
            ref="lyrtimeRef"
          >
            {{ item.txt }}
          </p>
        </div>
        <div class="lyc pure" v-else>
          <p>纯音乐，请欣赏！</p>
        </div>
      </div>
      <!-- 滚动条 -->
      <div class="bline bline-1">
        <span
          class="scroll"
          :style="{ height: 260 * (7 / lyric.length) + 'px' }"
          @mousedown="scrollHandle($event, 1)"
          ref="scrollRef1"
        ></span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { SongLriyc } from '@/api/song.js'
import { operationClick } from '@/utils/methods.js'
export default {
  data() {
    return {
      // 歌词
      lyric: '',
      // 歌曲列表滚动条定位高度
      top: 0,
      top1: 0,
      // 当前滚动的滚动条
      scroll: '',
      // 当前滚动的主体
      scrollMain: '',
      // 歌词报错按钮显示
      uploadDisplay: false,
      // 歌词定时器
      timerLyc: null
    }
  },
  methods: {
    // 歌曲列表鼠标滚动事件
    ScrollMouseMove(event) {
      // 鼠标滚动的距离
      let setTop = event.clientY - this.top
      const MainRef = this.$refs[this.scrollMain]
      let marginTop = -(setTop / 260) * MainRef.offsetHeight
      // 判断是否出界
      if (setTop < 0) {
        setTop = 0
      } else if (setTop > 260 - this.h) {
        setTop = 260 - this.h
      }
      if (marginTop > 0) {
        marginTop = 0
      } else if (marginTop < 260 - MainRef.offsetHeight) {
        marginTop = 260 - MainRef.offsetHeight
      }
      this.$refs[this.scrollref].style.top = setTop + 'px'
      MainRef.style.marginTop = marginTop + 'px'
    },
    // 歌曲列表鼠标按下事件
    scrollHandle(e, ref) {
      // 起始top值
      this.top = e.clientY - e.target.offsetTop
      // 滚动体高度
      this.h = e.target.offsetHeight
      const tempRef = this.$refs.listbdRef
      // 判断滚动在那个组件
      if (!ref) {
        this.scrollref = 'scrollRef'
        this.scrollMain = 'ulRef'
      } else {
        this.scrollref = 'scrollRef1'
        this.scrollMain = 'lycRef'
        // 如果拖动滚动条控制歌词时，自动定时器清除
        clearInterval(this.timerLyc)
        this.timerLyc = null
      }
      // console.log(ref)
      // 监听列表主体鼠标的滚动事件
      tempRef.addEventListener('mousemove', this.ScrollMouseMove)
      // 监听列表主体鼠标的抬起事件，解除滚动事件的监听
      tempRef.addEventListener('mouseup', () => {
        tempRef.removeEventListener('mousemove', this.ScrollMouseMove)
        if (ref && !this.paused) {
          setTimeout(() => {
            this.setLycInter()
          }, 1500)
        }
        // console.log('mouseup')
      })
      // 监听列表主体鼠标的离开事件，解除滚动事件的监听
      tempRef.addEventListener('mouseleave', () => {
        tempRef.removeEventListener('mousemove', this.ScrollMouseMove)
        if (ref && !this.paused) {
          setTimeout(() => {
            this.setLycInter()
          }, 1500)
        }
        // console.log('mouseout')
      })
    },
    // 鼠标齿轮滚动事件
    listbdcWheel(e, scrollmain, scroll) {
      // 如果是歌词滑动，清除自动定时器
      if (scroll === 'scrollRef1') {
        clearInterval(this.timerLyc)
        this.timerLyc = null
        if (this.timerTimeOut) {
          clearTimeout(this.timerTimeOut)
          this.timerTimeOut = null
        }
      }
      // 鼠标滚动的距离
      const top = scroll === 'scrollRef' ? this.top : this.top1
      let setTop = e.deltaY / 20 + top
      const scrollMain = this.$refs[scrollmain]
      const scrollRef = this.$refs[scroll]
      let marginTop = -(setTop / 260) * scrollMain.offsetHeight
      this.h = scrollRef.offsetHeight
      // 判断是否出界
      if (setTop < 0) {
        setTop = 0
      } else if (setTop > 265 - this.h) {
        setTop = 265 - this.h
      }
      if (marginTop > 0) {
        marginTop = 0
      } else if (marginTop < 260 - scrollMain.offsetHeight) {
        if (scroll === 'scrollRef1') {
          marginTop = 260 - scrollMain.offsetHeight - 32
        } else {
          marginTop = 260 - scrollMain.offsetHeight
        }
      }
      scrollRef.style.top = setTop + 'px'
      if (scroll === 'scrollRef') {
        this.top = setTop
      } else {
        this.top1 = setTop
      }
      scrollMain.style.marginTop = marginTop + 'px'
      this.timerTimeOut = setTimeout(() => {
        this.setLycInter()
      }, 1500)
    },
    // 获取歌词
    async getLyric() {
      if (!this.songList.length) {
        return
      }
      const id = this.currentSong.id || this.songList[this.playerSetting.index].id
      console.log('test-2 id', id)
      // const id = this.songList[this.playerSetting.index].id
      const { data: res } = await SongLriyc(id)
      const templrc = res.lrc.lyric
      const templist = templrc.split(/\n/g)
      const lyriclist = []
      templist.forEach((item, i) => {
        if (item.includes('][')) {
          const arrtemp = item.split(']')
          for (let i = 0; i < arrtemp.length - 1; i++) {
            const obj = {}
            obj.txt = arrtemp[arrtemp.length - 1]
            const time = arrtemp[i].slice(1)
            const m = time.split(':')[0]
            const s = time.split(':')[1]
            obj.time = parseInt(m) * 60 + parseFloat(s)
            lyriclist.push(obj)
          }
        } else {
          const obj = {}
          obj.txt = item.split(']')[1]
          const time = item.split(']')[0].slice(1)
          const m = time.split(':')[0]
          const s = time.split(':')[1]
          obj.time = parseInt(m) * 60 + parseFloat(s)
          lyriclist.push(obj)
        }
      })
      lyriclist.pop()
      // console.log(templist)
      lyriclist.sort((a, b) => a.time - b.time)
      this.lyric = lyriclist
      // console.log(templrc)
    },
    // 开启定时器，歌词自动下滑
    setLycInter() {
      if (this.$parent.paused) {
        clearInterval(this.timerLyc)
        this.timerLyc = null
      } else {
        if (this.$refs.lyrtimeRef && !this.timerLyc) {
          this.timerLyc = setInterval(() => {
            console.log('setLycInter')
            this.$refs.lyrtimeRef.forEach((item, index) => {
              if (parseInt(this.$parent.currentTime) === parseInt(item.dataset.time)) {
                for (let i = 0; i < this.$refs.lyrtimeRef.length; i++) {
                  if (i !== index) {
                    this.$refs.lyrtimeRef[i].classList.remove('current')
                  }
                }
                this.$refs.lyrtimeRef[index].classList.add('current')
                this.$refs.lycRef.style.transition = 'all 0.7s linear'
                this.$refs.lycRef.style.marginTop = -(index - 4 < 0 ? 0 : index - 4) * 32 + 'px'
                this.$refs.scrollRef1.style.top =
                  (index / this.$refs.lyrtimeRef.length) * 240 + 'px'
              }
            })
          }, 100)
        }
      }
    },
    // 播放列表点击事件
    songListClickHandle(index) {
      this.$store.commit('Music/setplayerSettingIndex', index)
    },
    // 从列表中删除
    delSong(id) {
      this.$store.commit('Music/popSongList', id)
    },
    // 收藏、分享
    operationClick
  },
  computed: {
    ...mapState({
      playerSetting: state => state.Music.playerSetting,
      songList: state => state.Music.songList,
      currentSong: state => state.Music.currentSong
    })
  },
  filters: {
    dtFormate(val) {
      const dt = new Date(val * 1000)
      const m = dt.getMinutes()
      const s = dt.getSeconds()
      return m.toString().padStart(2, '0') + ':' + s.toString().padStart(2, '0')
    },
    dtFormate2(val) {
      const m = Math.floor(val / 1000 / 60)
      const s = Math.floor((val / 1000) % 60)
      return m.toString().padStart(2, '0') + ':' + s.toString().padStart(2, '0')
    },
    arName(item) {
      let tempStr = ''
      item.forEach((ar, i) => {
        tempStr += i + 1 === item.length ? ar.name : ar.name + '/'
      })
      return tempStr
    }
  },
  watch: {
    'playerSetting.index'() {
      this.getLyric()
    }
  },
  created() {
    this.getLyric()
  }
}
</script>

<style lang="less" scoped>
@import url(./AudioPlayList.less);
</style>
